package mips.instructions;

import mips.structure.MipsInstr;
import mips.value.Immediate;
import mips.value.MipsValue;

public class Jr extends MipsInstr {
    public MipsValue op;
    public boolean isMain = false;
    private int stackOffset;

    public Jr(MipsValue op, boolean isMain, int stackOffset) {
        this.op = op;
        this.isMain = isMain;
        this.stackOffset = stackOffset;
    }

    public Jr(int stackOffset) {
        this.stackOffset = stackOffset;
    }

    // 在退出函数之前，对于非main函数，需要将返回值放到$v0中，之后还有函数尾声
    // 要将$ra恢复

    @Override
    public String toString() {
        if (isMain) {
            return "li $v0, 10\nsyscall";
        }
        // 函数尾声，将保存的寄存器恢复
        StringBuilder sb = new StringBuilder();
        if (op == null) {
            sb.append(handleStackOffset() + "jr $ra");
        } else if (op instanceof Immediate) {
            sb.append("li $v0, " + op + "\n" + handleStackOffset() + "jr $ra");
        } else {
            sb.append("move $v0, " + op + "\n" + handleStackOffset() + "jr $ra");
        }
        return sb.toString();
    }

    private String handleStackOffset() {
        return "lw $ra, " + (stackOffset - 4) + "($sp)\n" + "addi $sp, $sp, " + stackOffset + "\n";
    }
}
